
var UTF8Magic = String.fromCharCode(239, 187, 191);
var writeCounter = 0;
var root = '';
var scriptSrc = root;
var envScriptSrc = root + 'etc/';

var echo, readFile, args;

if (typeof WScript != 'undefined') {
	
	//
	// Windows Scripting Host
	//
	
	var forReading = 1, forWriting = 2, forAppending = 8, overwriteIfExist = -1, createIfNotExist = -1, failIfNotExit = 0, openAsDefault = -2, openAsASCII = 0, openAsUnicode = -1;
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	
	echo = function(msg) {
		WScript.Echo(msg);
	}
	
	readFile = function(filename, silentFail) {
		var str = '';
		try {
			var file = fso.OpenTextFile(filename, forReading, failIfNotExit, openAsDefault);
			str = file.AtEndOfStream ? '' : file.ReadAll();
			file.Close();
			if (str.substr(0, 3) == UTF8Magic)
				str = str.substr(UTF8Magic.length);	// remove UTF-8 magic numbers from string
		} catch(e) {
			if (silentFail)
				str = null;
			else
				echo('Exception reading file "' + filename + '"');
		}
		return str;
	}
	
	eval(readFile(envScriptSrc + 'env_wsh.js', true) || readFile('env_wsh.js', true));
	
} else if (typeof system != 'undefined' && system && typeof system.resource != 'undefined') {
	
	//
	// JSDB
	//
	
	echo = function(msg) {
		println(msg);
	}
	
	readFile = function(filename, silentFail) {
		var str = '';
		try {
			str = new Stream(filename).readText();
		} catch(e) {
			if (silentFail)
				str = null;
			else
				echo('Exception reading file "' + filename + '"');
		}
		return str;
	}
	
	eval(readFile(envScriptSrc + 'env_jsdb.js', true) || readFile('env_jsdb.js', true));
	
} else if (typeof print != 'undefined' && typeof java != 'undefined') {
	
	//
	// Rhino (Linux, Mac)
	//
	
	echo = function(msg) {
		print(msg);
	}
	
	for (var i = 0; i < arguments.length; ++i)
		args[i] = arguments[i];
	
	throw new Error('Rhino is not supported');
	
} else if (typeof system !== 'undefined' && typeof global !== 'undefined' && typeof include !== 'undefined' && typeof require !== 'undefined') {
	
	//
	// v8cgi
	//
	
	include('./env_v8cgi');
	echo = global.echo;
	readFile = global.readFile;
	args = global.args;

} else {
	throw new Error('Unsupported host environment!');
}

var scriptToRun = args.shift();
if (scriptToRun.charAt(0) != '.')
	scriptToRun = scriptSrc + scriptToRun;

eval(readFile(scriptToRun + '.js'));
